package com.tiantianyuegou.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.SpecListAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ColorOrSizeModel;
import com.tiantianyuegou.model.ProductModel;
import com.tiantianyuegou.model.SpecListModel;
import com.tiantianyuegou.model.SpecModel;
import com.tiantianyuegou.model.StoreModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.view.NoScrollListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 添加购物车或立即购买
 */
public class BuyActivity extends BaseActivity implements View.OnClickListener{
    private ImageView mImg_product, mImg_redPacket;
    private TextView mTxt_name, product_price,
            product_buy_count, product_desp, product_num_reduce, product_num_add, product_num, product_operation;
    private NoScrollListView product_spec_list;
    private SpecListAdapter mAdapter;
    private List<SpecListModel> mData;
    private List<SpecModel> mSpecData;
    private String type;//判断是购买还是添加购物车

    private LoadingDialog mLoadingDialog;

    private Map<Integer, Object> mSelectSpec = new HashMap<>();
    private int mStore;
    private String mTpId;
    private String mTscId;//购物车id
    private String mCount;//购买数量
    private String mProductName;//商品名字
    private String mProductPrice;//商品价格
    private String mProductPic;//商品图片
    private String mShopName;//店铺名称
    private int mShopId;//店铺Id
    private String mUnitPrice;//贯抵现值
    private String mCanUse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy);
    }
    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        //判断是否是从购物车界面跳转过来的
        if (!"edit".equals(type)) {
            mProductPic = intent.getStringExtra("productPic");
            mProductName = intent.getStringExtra("productName");
            mTpId = intent.getStringExtra("tpId");
            mShopId = intent.getIntExtra("shopId", 0);
            mShopName = intent.getStringExtra("shopName");
            mUnitPrice = intent.getStringExtra("unitPrice");
            mCount = "1";
            mCanUse=intent.getStringExtra("canUseGuan");
        } else {
            mImg_redPacket.setVisibility(View.GONE);
            Bundle bundle = new Bundle();
            bundle = getIntent().getExtras();
            ProductModel model = (ProductModel) bundle.get("model");
            mCount = model.getNumber();
            mTpId = model.getId() + "";
            mTscId = model.getTscId() + "";
            mProductName = model.getName();
            mProductPic = model.getUrl();
        }
        product_buy_count.setText(mCount);
        product_num.setText(mCount);
        mTxt_name.setText(mProductName);
        //加载商品图片
        ImageLoader.getInstance().init(
                ImageLoaderConfiguration.createDefault(BuyActivity.this));
        ImageLoader.getInstance().displayImage(mProductPic, mImg_product);

        Log.e("TAG","product pic:"+mProductPic);

        if ("shoppingCar".equals(type)) {
            product_operation.setText("加入购物车");
            product_operation.setBackgroundColor(getResources().getColor(R.color.color_ff7912));
        } else if ("buy".equals(type) || "edit".equals(type)) {
            product_operation.setText("确定");
            product_operation.setBackgroundColor(getResources().getColor(R.color.bg_button_normal));
        }



        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.show();
        //加载数据
        getGroupData(mTpId);
        // getListData(mTpId);
    }

    @Override
    public void findViewByIds() {
        mImg_product = (ImageView) findViewById(R.id.prodcut_img);
//        mImg_redPacket = (ImageView) findViewById(R.id.procuct_hongbao_img);
        mTxt_name = (TextView) findViewById(R.id.product_name);
        product_price = (TextView) findViewById(R.id.product_price);
        product_buy_count = (TextView) findViewById(R.id.product_buy_count);
        product_desp = (TextView) findViewById(R.id.product_desp);
        product_num_reduce = (TextView) findViewById(R.id.product_num_reduce);
        product_num_add = (TextView) findViewById(R.id.product_num_add);
        product_num = (TextView) findViewById(R.id.product_num);
        product_operation = (TextView) findViewById(R.id.product_operation);
        product_spec_list = (NoScrollListView) findViewById(R.id.product_spec_list);
    }


    @Override
    public void initListener() {
        product_num_reduce.setOnClickListener(this);
        product_num_add.setOnClickListener(this);
        product_operation.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mSpecData = new ArrayList<>();
        mData = new ArrayList<>();
        mAdapter = new SpecListAdapter(this);
        product_spec_list.setAdapter(mAdapter);
        mAdapter.setChangeSpecListener(new SpecListAdapter.IChangeSpecListener() {
            @Override
            public void changeSpec(int position, ColorOrSizeModel model) {
                mSelectSpec.put(position, model);
                StringBuffer desp = new StringBuffer();
                for (int i = 0; i < mSelectSpec.size(); i++) {
                    ColorOrSizeModel item = (ColorOrSizeModel) mSelectSpec.get(i);
                    desp.append(item.getLabel()).append("、");
                }
                product_desp.setText(desp.toString().substring(0,desp.length()-1));
                getPrice(desp.toString().substring(0,desp.length()-1));
            }
        });

    }

    //通过比较获取所选的规格所对应的价格
    private void getPrice(String desp) {
        Log.e("TAG","desp:"+ desp.toString());
        for (int i = 0; i < mSpecData.size(); i++) {
            StringBuffer spec = new StringBuffer();
            List<SpecModel.Spec> list = mSpecData.get(i).getSpec();
            for (int j = 0; j < list.size(); j++) {
                spec.append(list.get(j).getChildName()).append("、");
            }
            Log.e("TAG", "spec:"+spec.toString());
            if (desp.equals(spec.toString().substring(0,spec.length()-1))) {
                changeSelect();
                mSpecData.get(i).setIsChoose(true);
                //  Log.e("TAG", "price" + mSpecData.get(i).getSpecPrice());
                Double price = Double.valueOf(mSpecData.get(i).getSpecPrice());
                product_price.setText("￥" + new DecimalFormat("0.00").format(price));
                mStore = mSpecData.get(i).getSpecStore();
                //当更改规格时，将购买的值置为1
                product_num.setText("1");
                product_buy_count.setText("1");
                break;
            }
        }
    }

    //取消用户选择的规格信息
    private void changeSelect() {
        for (int i = 0; i < mSpecData.size(); i++) {
            mSpecData.get(i).setIsChoose(false);
        }
    }

    @Override
    public void onClick(View v) {
        int num = Integer.valueOf(product_num.getText().toString());
        switch (v.getId()) {
            case R.id.product_num_reduce:
                if (1 == num) {
                    //减到1不允许在减
                } else {
                    --num;
                    product_num.setText(num + "");
                    product_buy_count.setText(num + "");
                }
                break;
            case R.id.product_num_add:
                if (num >= mStore) {
                    //购买数大于等于库存的时候，不允许加
                } else {
                    ++num;
                    product_num.setText(num + "");
                    product_buy_count.setText(num + "");
                }
                break;
            case R.id.product_operation:
                mCount = product_buy_count.getText().toString();
                mProductPrice = product_price.getText().toString();
                StringBuffer specIds = new StringBuffer();
                StringBuffer specValueIds = new StringBuffer();
                StringBuffer specStr = new StringBuffer();
                //获取商品规格ID
                for (int i = 0; i < mSpecData.size(); i++) {
                    if (mSpecData.get(i).isChoose()) {
                        List<SpecModel.Spec> spec = mSpecData.get(i).getSpec();
                        for (int j = 0; j < spec.size(); j++) {
                            //获取商品规格ID
                            specIds.append(spec.get(j).getGroupId()).append(",");
                            //获取商品规格值id
                            specValueIds.append(spec.get(j).getChildId()).append(",");
                            //拼接用户选择的规格内容
                            specStr.append(spec.get(j).getGroupName()).append(":");
                            specStr.append(spec.get(j).getChildName()).append(" ");
                        }
                    }
                }
                if (specIds.length() > 0) {
                    if ("buy".equals(type)) {
                        Intent intent = new Intent(BuyActivity.this, ConfirmOrderActivity.class);
                        intent.putExtra("type", "buy");
                        intent.putExtra("whereIn", "2");
                        intent.putExtra("unitPrice",mUnitPrice);
                        ArrayList<StoreModel> storeModels = new ArrayList<>();
                        StoreModel storeModel = new StoreModel();
                        storeModel.setStoreId(mShopId);
                        storeModel.setStoreName(mShopName);

                        ArrayList<ProductModel> productModels = new ArrayList<>();

                        ProductModel productModel = new ProductModel();
                        productModel.setId(Integer.parseInt(mTpId));
                        productModel.setPrice(mProductPrice);
                        productModel.setName(mProductName);
                        productModel.setStore(mStore);
                        Log.e("TAG", "store:" + productModel.getStore());
                        productModel.setSpec(specStr.toString());
                        productModel.setSpecIds(specIds.substring(0, specIds.length() - 1));
                        productModel.setSepecValueIds(specValueIds.substring(0, specValueIds.length() - 1));
                        productModel.setUrl(mProductPic);
                        productModel.setNumber(mCount);

                        productModels.add(productModel);
                        storeModel.setProductModels(productModels);
                        storeModel.setTotalGuan(SPHelper.getTmGuanCount());
                        storeModel.setExpress("0.00");
                        storeModel.setUnitPrice(mUnitPrice);
                        //当个人的总贯数小于该店铺中的总贯数的时候，可用贯显示我的总贯数
                        if(Integer.valueOf(mCanUse)>Integer.valueOf(SPHelper.getTmGuanCount())){
                            storeModel.setCanUseGuan(SPHelper.getTmGuanCount());
                        }else{
                            storeModel.setCanUseGuan(mCanUse);
                        }
                        storeModels.add(storeModel);
                        intent.putExtra("orderInfo", storeModels);

                        startActivity(intent);
                    } else if ("shoppingCar".equals(type)) {
                        mLoadingDialog.setMsg("正在添加到购物车");
                        mLoadingDialog.show();

                        //添加到购物车
                        addShoppingCar(mCount, specIds.substring(0, specIds.length() - 1),
                                specValueIds.substring(0, specValueIds.length() - 1));
                    } else if ("edit".equals(type)) {
                        mLoadingDialog.setMsg("正在修改购物车商品");
                        mLoadingDialog.show();
                        upadateShoppingCar(mCount, specIds.substring(0, specIds.length() - 1),
                                specValueIds.substring(0, specValueIds.length() - 1));
                    }
                }
                break;
        }
    }


    //更新购物车
    private void upadateShoppingCar(String count, String specIds, String specValueIds) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tscId", mTscId);
        params.addBodyParameter("count", count);
        params.addBodyParameter("specIds", specIds);
        params.addBodyParameter("specValueIds", specValueIds);
        Log.e("TAG", "request params is:" + mTscId + ":" + count + ":" + specIds + ":" + specValueIds);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.UPDATE_CAR, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "update shoppingcar response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("提交更新失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            showMsg("更新成功");
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure ;" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }


    //添加商品到购物车
    private void addShoppingCar(String count, String specIds, String specValueIds) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("tpId", mTpId);
        params.addBodyParameter("count", count);
        params.addBodyParameter("specIds", specIds);
        params.addBodyParameter("specValueIds", specValueIds);
        Log.e("TAG", "request params is:" + SPHelper.getTmId() + ":" + mTpId + ":" + count + ":" + specIds + ":" + specValueIds);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADD_CAR, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();

                Log.e("TAG", "add to shopping car:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("加入购物车失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            setResult(Constant.ADD_SHOPPING_CAR_RESULT);
                            finish();
                        } else {
                            showMsg("加入购物车失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("TAG", "解析出错");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "request failure ;" + s);
                showMsg("当前网络不可用，请检查您的网设置");
                mLoadingDialog.dismiss();

            }
        });

    }

    //获取商品规格和价格
    private void getGroupData(String tpId) {
//        http://hjtech.wicp.net:8080/tiantianyuegou-api/product/detail?tgId=358&tmId=1216
        RequestParams params = new RequestParams();
//        params.addBodyParameter("tpId", tpId);
//        Log.e("TAG", "params tpId is:" + tpId);
        params.addBodyParameter("tgId",358+"");
        params.addBodyParameter("tmId",1216+"");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GOODS_DETAIL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "response data:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("该商品暂无规格信息");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            mSpecData.clear();
                            JSONArray list = root.getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                SpecModel model = new SpecModel();
                                JSONObject value = list.getJSONObject(i);
                                JSONArray spec = value.getJSONArray("spec");
                                List<SpecModel.Spec> specList = new ArrayList<SpecModel.Spec>();
                                for (int j = 0; j < spec.length(); j++) {
                                    SpecModel.Spec specModel = new SpecModel.Spec();
                                    JSONObject specValue = spec.getJSONObject(j);
                                    specModel.setGroupId(specValue.getInt("tsId"));
                                    specModel.setGroupName(specValue.getString("tsName"));
                                    specModel.setChildId(specValue.getInt("tpsId"));
                                    specModel.setChildName(specValue.getString("tpsSpecValue"));
                                    specList.add(specModel);
                                }
                                model.setSpec(specList);
                                model.setSpecPrice(value.getString("tpsSpecPrice"));
                                model.setSpecStore(value.getInt("tpsSpecStore"));
                                model.setIsChoose(false);
                                mSpecData.add(model);
                            }
                            getListData(mTpId);//获取规格值列表
                        } else if ("101".equals(code)) {
                            //showMsg("查询失败");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "request failure ;" + s);
                showMsg("当前网络不可用，请检查您的网设置");
                mLoadingDialog.dismiss();

            }
        });
    }

    //获取规格列表数据
    private void getListData(String categoryId) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("productId", categoryId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GOODS_SPECIFICATION_LIST_BUY, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "getListData reponse data" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("该商品暂无规格信息");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            mData.clear();
                            JSONArray list = root.getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                SpecListModel model = new SpecListModel();
                                JSONObject value = list.getJSONObject(i);
                                model.setTitle(value.getString("tsName"));
                                model.setTitleId(value.getInt("tpsSpecId"));
                                JSONArray values = value.getJSONArray("values");
                                List<ColorOrSizeModel> specList = new ArrayList<ColorOrSizeModel>();
                                for (int j = 0; j < values.length(); j++) {
                                    ColorOrSizeModel specModel = new ColorOrSizeModel();
                                    JSONObject specValue = values.getJSONObject(j);
                                    specModel.setId(specValue.getInt("tpsId"));
                                    specModel.setLabel(specValue.getString("tpsSpecValue"));
                                    specList.add(specModel);
                                }
                                model.setValues(specList);
                                mData.add(model);
                            }
                            //设置第一个属性为勾选
                            StringBuffer desp = new StringBuffer();
                            for (int i = 0; i < mData.size(); i++) {
                                mData.get(i).getValues().get(0).setIsSelect(true);
                                desp.append(mData.get(i).getValues().get(0).getLabel()).append("、");
                                mSelectSpec.put(i, mData.get(i).getValues().get(0));
                            }
                            //设置默认规格属性
                            product_desp.setText(desp.toString().substring(0,desp.length()-1));
                            getPrice(desp.toString().substring(0,desp.length()-1));//获取默认规格商品的价格
                            mAdapter.setData(mData);
                            mAdapter.notifyDataSetChanged();
                        } else if ("103".equals(code)) {
                            showMsg("该商品暂无规格数据");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure ;" + s);
                showMsg("当前网络不可用，请检查您的网络设置");
            }
        });
    }
}
